/*
 * SecureContainer.h
 *
 *  Created on: Aug 26, 2011
 *      Author: Gherman Alin
 */

#ifndef SECURECONTAINER_H_
#define SECURECONTAINER_H_

#include <istream>
#include <ostream>
#include <map>
#include "serialization.h"
#include "TemplateMap.h"

namespace DataAccess {

class SecureContainer {
	friend class boost::serialization::access;

	template<class Archive>
	void save(Archive & ar, const unsigned int version) const {
		encrypt();
		ar & _encryptionType;
		ar & _crypted;
	}
	template<class Archive>
	void load(Archive & ar, const unsigned int version) {
		ar & _encryptionType;
		ar & _crypted;
		loaded = true;
		decrypt();
	}
	BOOST_SERIALIZATION_SPLIT_MEMBER()

public:
	SecureContainer();
	SecureContainer(const std::string& _password);
	virtual ~SecureContainer();

	bool hasPassword();
	void setPassword(const std::string& password);
	bool setPasswordAndDecrypt(const std::string& password);

	std::vector<std::string> getKeys();

	bool set(const std::string& key, const std::string& value);
	bool set(const std::string& key, const std::vector<char>& data);
	bool set(const std::string& key, std::istream& inData);

	bool getStr(const std::string& key, std::string& outValue);
	bool getData(const std::string& key, std::vector<char>& outData);
	bool getInOutstream(const std::string& key, std::ostream& out);

	bool remove(const std::string& key);

private:
	std::string password;
	StringMap strData;
	BytesMap rawData;

	bool decrypted;
	bool loaded;

	mutable std::string _crypted;
	mutable long _encryptionType;

	void encrypt() const;
	bool decrypt();
};

}

#endif
